package com.servlets;

import java.io.IOException;
import java.sql.SQLException;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.DisplayChatters;
import com.NicknameValidation;

public class StartServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		ServletContext servletContext = this.getServletContext();
		WebApplicationContext webcontext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
		NicknameValidation valid = (NicknameValidation) webcontext.getBean("nicknameValidation");

		try {
			if (valid.validate(request.getParameter("login"))) {
				if (request.getParameter("login") != null) {
					request.getSession().setAttribute("nickname", request.getParameter("login"));

					RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/chat.jsp");
					dispatcher.forward(request, response);
					return;
				}
			}
		} catch (SQLException | NamingException e1) {
			e1.printStackTrace();
		}
		DisplayChatters display = (DisplayChatters) webcontext.getBean("displayChatters");
		try {
			request.getSession().setAttribute("users", display.getUsers());
		} catch (ClassNotFoundException | SQLException | NamingException e) {
			e.printStackTrace();
		}

		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/start.jsp");
		dispatcher.forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		doGet(request, response);
	}

}
